<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta http-equiv="pragma" content="no-cache"> 
	    <meta http-equiv="Cache-Control" content="no-cache, must-revalidate"> 
	    <meta http-equiv="expires" content="0">
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
		<link rel="stylesheet" href="../css/mui.min.css" />
		<link rel="stylesheet" href="../css/mui.picker.css" />
		<link rel="stylesheet" href="../css/mui.poppicker.css" />
		<link rel="stylesheet" href="../css/common.css" />
	</head>
	<style type="text/css">
		* {
			margin: 0px;
			padding: 0px;
		}
		body {
			background-color: #F3F3F3;
		}
		.mui-content {
			width: 100%;
			height: 100%;
			background-color: #F3F3F3;
		    -webkit-overflow-scrolling: touch;
		}
		.title-div {
			margin-top: 24px;
			width: 100%;
			text-align: center;
		}
		.title-icon {
			width: 17px;
			height: 17px;
		}
		.title-span {
			color: #444444; 
			font-size: 18px; 
			font-family: 'PingFang-SC-Regular';
		}
		.person-div {
			margin-top: 14px;
			width: 100%;
			background-color: #FFFFFF;
		}
		.item-div {
			margin-left: 14px;
			margin-right: 14px;
			height: 49px;
			position: relative;
		}
		.item-header {
			margin-left: 14px;
			margin-right: 14px;
			height: 49px;
			position: relative;
		}
		.item-header-icon {
			width: 33px;
			height: 33px;
			float: right;
			margin-right: 56px;
			margin-top: 8px;
		}
		.item-span {
			font-size: 13px;
			color: #444444;
			line-height: 49px;
			font-family: "PingFang-SC-Regular";
		}
		.item-content-span {
			font-size: 13px;
			color: #444444;
			font-family: "PingFang-SC-Regular";
			line-height: 49px;
			margin-right: 56px;
			white-space: nowrap;  
			text-align: right;
		    width: 180px;   
		    overflow: hidden;   
		    text-overflow:ellipsis;  
		    position: absolute;
		    right: 0px;
		    top: 0px;
		}
		.item-icon {
			width: 14px;
			height: 3px;
			position: absolute;
			right: 14px;
			top: 23px;
		}
		.line-div {
			width: 92%;
			height: 1px;
			margin-left: 4%;
			background-color: #F3F3F3;
		}
		input[type=text] {
			padding: 0px;
		    float: right;
    			width: 60%;
    			margin-right: 56px;
			margin-top: 4px;
			margin-bottom: 0;
			height: 50px; 
			border-width: 0px;
			color:#515151;
			font-size: 15px;
			text-align: end;
			background-color: transparent;
		}
		.item-textarea {
			margin-left: 14px;
			margin-right: 14px;
			position: relative;
		}
		textarea {
		    color: gray;
		    height: 50px;
		    width: 70%;
		    margin-top: 15px;
		    vertical-align: middle;
		    font-size: 15px;
		    padding: 0px;
    			padding-left: 10px;
    			border-color: #FFFFFF;
		}
		.upload-img {
			float: right;
			margin-right: 56px;
			margin-top: 8px;
			width: 33px;
			height: 33px;
			margin-left: 4%;
			background: url(../img/evaluation/SC.png) no-repeat;
			background-size: 100% 100%;
		}
		.upload-img input::-webkit-file-upload-button {
            width: 33px;
            height: 33px;
            border: none;
            position: absolute;
            outline: 0;
            opacity: 0;
        }
        .upload-img input#file {
            display: block;
            width: auto;
            border: 0;
            vertical-align: middle;
        }
	</style>
	<body>
		<div class="mui-content">
			<div class="title-div">
				<span class="title-span">个人信息</span>
			</div>
			<div class="person-div">
				<div class="item-header" data-id="0">
					<span class="item-span">头像</span>
					<div class="upload-img">
						<input class="huodong-msg" type="file" name="file" id="file" value="" accept="image/*" multiple onchange="handleInputChange();" />
					</div>
					<!--<img class="item-header-icon" src="../img/index/chihuo_icon.png" />-->
					<img class="item-icon" src="../img/common/more_icon.png" />
				</div>
				<div class="line-div"></div>
				<div class="item-div" data-id="1">
					<span class="item-span">姓名</span>
					<input type="text" id="name" placeholder="点击输入姓名"/>
				</div>
				<div class="line-div"></div>
				<div id="showUserPicker" class="item-div" data-id="2">
					<span class="item-span">性别</span>
					<span id="sexId" class="item-content-span"></span>
					<img class="item-icon" src="../img/common/more_icon.png" />
				</div>
				<div class="line-div"></div>
				<div class="item-div" data-id="3">
					<span class="item-span">星座</span>
					<span id="constellationId" class="item-content-span"></span>
					<img class="item-icon" src="../img/common/more_icon.png" />
				</div>
				<div class="line-div"></div>
				<div class="item-div" data-id="4">
					<span class="item-span">地址管理</span>
					<img class="item-icon" src="../img/common/more_icon.png" />
				</div>
				<div class="line-div"></div>
				<div class="item-textarea">
					<span class="item-span">个性签名</span>
					<textarea id="signatureId" placeholder="点击输入个性签名"></textarea>
				</div>
			</div>
			<div class="bottom-div">
				<div class="back-div"><a class="mui-action-back" onclick="javascript:history.back(-1)"><img style="width: 10px; margin-top: 15px;" src="../img/common/back_icon.png" /></a></div>
				<div class="event-div">保存</div>
			</div>
		</div>
	</body>
	<script type="text/javascript" src="../js/thirdparty/mui.min.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/jquery-3.3.1.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/spin.min.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/mui.picker.js" ></script>
	<script type="text/javascript" src="../js/thirdparty/mui.poppicker.js" ></script>
	<script type="text/javascript" src="../js/utils/boot.js" ></script>
	<script type="text/javascript">
		"use strict";
		mui.init();
		var sexPicker = null;
		var constellationPicker = null;
		var userID = base.getParameter("userID");
		var tempHeadImg = "";
		(function($, doc) {
			$.init();
			getPersonalInfo();
			$.ready(function() {
				sexPicker = new $.PopPicker();
				sexPicker.setData(["男","女"]);
				constellationPicker = new $.PopPicker();
				constellationPicker.setData(["白羊座", "金牛座", "双子座","巨蟹座","狮子座","处女座","天秤座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"]);
			});
		})(mui, document);
		function getPersonalInfo() {
			base.setWait('正在获取数据...');
			var url = base.url.getPersonalInfo;
			var data = {
				userID: userID
			}
			base.postData(url,data,getPersonalInfoSuccess);
		}
		function getPersonalInfoSuccess(data) {
			base.clearWait();
			if (data.success) {
				var _headImg = data.context.headImg;
				tempHeadImg = _headImg;
				if (_headImg != "" && _headImg != null) {
					$(".upload-img").css({"background": "url("+_headImg+")", "background-size": "100% 100%"});
				}
				$("#name").val(data.context.name);
				$("#sexId").text(data.context.sex==1?"男":"女");
				$("#constellationId").text(data.context.constellation);
				$("#signatureId").text(data.context.signature);
			} else {
				mui.toast(data.msg);
			}
		}
		$('.person-div').on('tap', 'div[class="item-div"]', function() {
			var typeID = $(this).data('id');
			if (typeID == 1) {
				return;
			}
			document.activeElement.blur();
			switch (typeID){
				case 2:
					sexPicker.show(function(items) {
						$("#sexId").text(items[0]);
						//返回 false 可以阻止选择框的关闭
						//return false;
					});
					break;
				case 3:
					constellationPicker.show(function(items) {
						$("#constellationId").text(items[0]);
						//返回 false 可以阻止选择框的关闭
						//return false;
					});
					break;
				case 4:
					window.location.href = "addressManagement.html?userID="+userID;
					break;
				default:
					break;
			}
		});
		$('.bottom-div').on('tap', '.back-div', function() {
			document.activeElement.blur();
			mui.back();
		})
		$('.bottom-div').on('tap', '.event-div', function() {
			document.activeElement.blur();
			base.setWait('正在保存数据...');
			var _sexStr = $("#sexId").text();
			var url = base.url.updatePersonalInfo;
			var params = {
				userID: userID,
				name: $("#name").val(),
				headImg: tempHeadImg,
				signature: $("#signatureId").val(),
				sex: _sexStr=="男"?1:2,
				constellation: $("#constellationId").text()
			}
			base.postData(url,params,function(data) {
				base.clearWait();
				mui.toast(data.msg);
			});
		})
		var fileData = {};//文件资源
		var imgFile = {};//文件信息
		function handleInputChange(){
			//先判断是否已有五张图片
			fileData = event.target.files[0];
			const imgMasSize = 1024 * 1024 * 5; // 5MB
			// 检查文件类型
		    if(['jpeg', 'png', 'gif', 'jpg'].indexOf(fileData.type.split("/")[1]) < 0){
		        mui.toast("文件类型仅支持 jpeg/png/gif！");
		        return;
		    }
		    // 文件大小限制
		    if(fileData.size > imgMasSize ) {
		        // 文件大小自定义限制
		        mui.toast("文件大小不能超过5MB！");
		        return;
		    }
			var imglengs = $(".comments-img").find(".close-div");
			if (imglengs.length >= 5) {
				mui.toast("最多只能上传五张图片");
				return;
			}
//			var paths = getObjectURL(fileData);
//			uploadFile(fileData);
			// 判断是否是ios
		    if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
		        // iOS
		        uploadFile(fileData);
		    } else {
		    		transformFileToDataUrl(fileData);
		    }
		}
		// 将file转成dataUrl
		function transformFileToDataUrl (file) {
		    const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩
		
		    // 存储文件相关信息
		    imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况
		    imgFile.size = file.size;
		    imgFile.name = file.name;
		    imgFile.lastModifiedDate = file.lastModifiedDate;
		
		    // 封装好的函数
		    const reader = new FileReader();
		
		    // file转dataUrl是个异步函数，要将代码写在回调里
		    reader.onload = function(e) {
		        const result = e.target.result;
		
		        if(result.length < imgCompassMaxSize) {
		            compress(result, processData, false);    // 图片不压缩
		        } else {
		            compress(result, processData, true);            // 图片压缩
		        }
		    };
		
		    reader.readAsDataURL(file);
		}
		// 使用canvas绘制图片并压缩
		function compress (dataURL, callback, shouldCompress) {
		    const img = new window.Image();
		
		    img.src = dataURL;
		
		    img.onload = function () {
		        const canvas = document.createElement('canvas');
		        const ctx = canvas.getContext('2d');
		
		        canvas.width = img.width;
		        canvas.height = img.height;
		
		        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
		
		        var compressedDataUrl;
		
		        if(shouldCompress){
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2);
		        } else {
		            compressedDataUrl = canvas.toDataURL(imgFile.type, 1);
		        }
		
		        callback(compressedDataUrl);
		    }
		}
		function processData (dataUrl) {
		    // 这里使用二进制方式处理dataUrl
		    const binaryString = window.atob(dataUrl.split(',')[1]);
		    const arrayBuffer = new ArrayBuffer(binaryString.length);
		    const intArray = new Uint8Array(arrayBuffer);
//		    const imgFile = this.imgFile;
		    for (var i = 0, j = binaryString.length; i < j; i++) {
		        intArray[i] = binaryString.charCodeAt(i);
		    }
		    const data = [intArray];
		
		    var blob;
		
		    try {
		        blob = new Blob(data, { type: imgFile.type });
		    } catch (error) {
		        window.BlobBuilder = window.BlobBuilder ||
		            window.WebKitBlobBuilder ||
		            window.MozBlobBuilder ||
		            window.MSBlobBuilder;
		        if (error.name === 'TypeError' && window.BlobBuilder){
		            const builder = new BlobBuilder();
		            builder.append(arrayBuffer);
		            blob = builder.getBlob(imgFile.type);
		        } else {
		            mui.toast("版本过低，不支持图片压缩");
		            throw new Error('版本过低，不支持上传图片');
		        }
		    }
		    // blob 转file
		    const fileOfBlob = new File([blob], imgFile.name);
		    uploadFile(fileOfBlob)
		}
		
		//上传图片
		function uploadFile(imgfile){
//			base.setWait("正在上传...");
			mui.toast("正在上传，请稍等...");
			var formData = new FormData();
			formData.append('file', imgfile);
	//		formData.append('myfile', $('input[name=file]')[0].files[0]);
			$.ajax({
	            url: base.url.uploadFile,
	            method: 'POST',
	            data: formData,
	            contentType: false, // 注意这里应设为false
	            processData: false,
	            cache: false,
	            success: function(data) {
//	            	base.clearWait();
	            	data = JSON.parse(data);
	            	pingImgPaths(data.obj);
	            },
	            error: function (jqXHR) {
//	            	base.clearWait();
	                console.log(JSON.stringify(jqXHR));
	            }
	        })
		}
		function pingImgPaths(path) {
			tempHeadImg = path;
			$(".upload-img").css({"background": "url("+path+")", "background-size": "100% 100%"});
		}
		//建立一個可存取到該file的url
		function getObjectURL(file) {
			var url = null ;
			if (window.createObjectURL!=undefined) { // basic
				url = window.createObjectURL(file);
			} else if (window.URL!=undefined) { // mozilla(firefox)
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL!=undefined) { // webkit or chrome
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		}
	</script>
</html>
